<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useSetRole } from '@/api/systemRole';
import { handleMessage } from '@/utils/globalEvent';
import type { ISetRoleParams } from '@/api/systemRole/type';
import type { FormInstance } from 'element-plus';

const emits = defineEmits(['handleRole']);
// btnLoading
const btnLoading = ref(false);
const btnLoadingTitle = '请求中';
const formRef = ref<FormInstance>();
// 新增用户弹窗
const dialogVisible = ref(false);
// 用户数据
const roleParams = ref<ISetRoleParams>({
	id: undefined,
	role: '',
});
// 验证规则
const roleRules = reactive({
	role: [
		{ required: true, message: '请填写角色名~', trigger: 'blur' },
		{ min: 3, max: 9, message: '角色名长度在3-9位~', trigger: 'blur' },
	],
});

// 关闭新增角色弹窗前回调
const handleDialogClose = () => {
	if (roleParams.value.id) roleParams.value.id = undefined;
	formRef.value?.resetFields();
	dialogVisible.value = false;
};
// 打开弹窗
const openDialog = (params: ISetRoleParams) => {
	const { id = undefined, role = '' } = params;
	if (id && role) {
		roleParams.value = {
			id,
			role,
		};
	}
	dialogVisible.value = true;
};
// 提交
const clickSubmit = () => {
	formRef.value?.validate(async isOk => {
		if (!isOk) return;
		btnLoading.value = true;
		try {
			const result = await useSetRole(roleParams.value);
			if (!result) return;
			handleMessage(result);
			handleDialogClose();
			emits('handleRole');
		} catch (error) {
			throw new Error('角色操作未知异常,请联系开发人员');
		} finally {
			btnLoading.value = false;
		}
	});
};

defineExpose({
	openDialog,
});
</script>

<template>
	<el-dialog v-model="dialogVisible" title="角色" :before-close="handleDialogClose">
		<el-form ref="formRef" :model="roleParams" :rules="roleRules">
			<el-form-item prop="role">
				<el-input v-model="roleParams.role"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button v-btn-loading:[btnLoadingTitle]="btnLoading" @click="clickSubmit">提 交</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<style lang="less" scoped>
@import url('./index.less');
</style>
